﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using TA.Bluetooth;
using System.IO;
using System.Threading;

namespace BTServerCE
{
    public class BTServer
    {
        #region members
        private List<string> commandList;
        private Thread bt_thread;
        private bool test;
        private BluetoothService service;
        private bool reached;
        #endregion

        #region constructor & destructor
        public BTServer(bool test)
        {
            this.test = test;


            // check if Bluetooth-Stick is available
            if (BluetoothRadio.IsSupported)
            {
                // Device visible for others
                // RadioMode setting not supported as long as the
                // WinCE image doesn't include the BthUtil.dll
                // BluetoothRadio.PrimaryRadio.Mode = 
                //     BluetoothRadioMode.Discoverable;

                // set device Name
                BluetoothRadio.PrimaryRadio.Name = "Robot Application";
                // desired service
                // Guid serviceId = BluetoothServiceList.Robot09;
                Guid serviceId = BluetoothServiceList.Robot21;

                // start new service
                service = new BluetoothService();
                service.CreateService(serviceId);
                if (test)
                Console.WriteLine("Service " + serviceId.ToString() + " started.");
            }
            else
            {
                if (test)
                Console.WriteLine("No Bluetooth-Stick is available");
                return;
            }



            bt_thread = new Thread(bt_Thread);
            bt_thread.Start();
        }
        #endregion

        #region methods
        public void clearList()
        {
            commandList.Clear();
        }

        public String getCommandAt(int i)
        {
            return this.commandList.ElementAt(i);
        }

        public bool startReached()
        {
            return reached;
        }

        private void bt_Thread()
        {
            BluetoothClient client;
            System.Net.Sockets.NetworkStream ns;
            bool bActive = true;
            if (test)
                Console.WriteLine("wait for incoming connections...");

            while (bActive)
            {
                // accept bluetooth connection
                client = service.WaitForConnection();
                if (test)
                Console.WriteLine("Incoming connection " + client.GetSocket().RemoteEndPoint);

                // transform into network stream
                ns = client.GetStream();

                // Read data to stream
                try
                {
                    using (StreamReader reader = new StreamReader(ns))
                    {
                        // Loop over the lines in the stream.
                        string line;
                        commandList = new List<string>();
                        while ((line = reader.ReadLine()) != null)
                        {
                            commandList.Add(line); 
                            if(line.Equals("Start"))
                                reached = true;                            
                        }
                    }
                }
                catch (Exception e) { if (test) Console.WriteLine(e); }

                if (test)
                {
                    int count = 0;
                    foreach (string cmd in commandList)
                    {
                        count++;
                        Console.WriteLine("Line {0}: {1}", count, cmd);
                        if (!startReached())
                            Console.WriteLine("Start noch nicht erreicht" + commandList.Last<string>());
                        else
                            Console.WriteLine("Start erreicht");
                    }
                }

                // clear and close stream
                client.Close();
                if(startReached()){
                    bActive = false;
                }
            }
        }
        #endregion

        #region main
        //static void Main(string[] args)
        //{
        //    BTServerCE server = new BTServerCE(true);
        //}
        #endregion
    }
}
